package com.example.myys.network.xsPlugins

import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONObject
import com.example.myys.Constants
import com.example.myys.data.entity.ChapterBean
import com.example.myys.data.entity.DataBean
import com.example.myys.data.repository.SettingLinkRepository
import com.example.myys.network.HttpClient
import com.example.myys.network.parse.HtmlParse
import com.example.myys.util.FileUtil
import org.jsoup.Jsoup
import org.jsoup.nodes.Element

//笔趣阁
class BQGParse : HtmlParse() {
    private val isChecked = SettingLinkRepository.getSettingByTypeIsChecked(Constants.XS)
    private val dataJson =
        if (isChecked != null) JSON.parseObject(isChecked.value) else JSON.parseArray(
            FileUtil.fileToJsonStr("xsjk.json")
        ).getJSONObject(0)

    override suspend fun getDataRecommend(createDate: String): List<DataBean> {
        var bookList = ArrayList<DataBean>()
        val url = dataJson.getString("url");
        val tj = dataJson.getJSONObject("tj")
        var tjUrl = tj.getString("url")
        if (!tjUrl.startsWith("http")) {
            tjUrl = url + tjUrl
        }
        var html = HttpClient.get(tjUrl, mapOf(), dataJson.getString("ecode"))
        if (html == null || html.isEmpty()) {
            return bookList
        }
        val document = Jsoup.parse(html)
        val tjList = tj.getJSONObject("list")
        val tjXpath = tjList.getString("xpath")
        val elementList = document.select(tjXpath)
        val tjListItem = tjList.getJSONObject("item")
        val tjListItemXpath = tjListItem.getString("xpath")
        val elements = elementList.select(tjListItemXpath)
        for (element in elements) {
            var bookBean = DataBean()
            tjListItem.getString("image").let {
                bookBean.cover = element.select(it).attr("src")
            }
            tjListItem.getString("name").let {
                bookBean.name = element.select(it).text()
            }
            tjListItem.getString("url").let {
                bookBean.url = element.select(it).attr("href")
            }
            tjListItem.getString("zz").let {
                bookBean.author = element.select(it).text()
            }
            tjListItem.getString("jj").let {
                bookBean.desc = element.select(it).text()
            }

            bookList.add(bookBean)
        }
        return bookList
    }

    override suspend fun getDataInfo(dataUrl: String): DataBean {
        var dataBean = DataBean()
        var chapterList = ArrayList<ChapterBean>()
        val url = dataJson.getString("url") + dataUrl
        val xq = dataJson.getJSONObject("xq");
        val html: String? = HttpClient.get(url, mapOf())
        if (html == null) {
            return dataBean;
        }
        val document = Jsoup.parse(html)
        val bookinfo = document.select(xq.getString("js"))
        dataBean.name = bookinfo.select(xq.getString("mc")).html()
        dataBean.cover = bookinfo.select(xq.getString("tp")).attr("src")
        dataBean.author = bookinfo.select(xq.getString("zz")).html()
        dataBean.status = bookinfo.select(xq.getString("zxzt")).html()
        dataBean.updateTime = bookinfo.select(xq.getString("gxsj")).html()
        dataBean.desc = bookinfo.select(xq.getString("jj")).text()
        val zj = xq.getJSONObject("zj")
        val booklistmain = document.select(zj.getString("xpath")).get(0)
        val item = zj.getJSONObject("item");
        val listmaindds = booklistmain.getElementsByTag(item.getString("xpath"))
        for ((index, listmaindd: Element) in listmaindds.withIndex()) {
            var chapter = ChapterBean()
            chapter.name = listmaindd.select(item.getString("nmae")).text()
            chapter.url = listmaindd.select(item.getString("url")).attr("href")
            if (!chapter.url.endsWith(".html")) {
                continue
            }
            chapter.index = index
            chapterList.add(chapter)
        }
        dataBean.chapters = chapterList
        return dataBean;
    }

    override suspend fun getChapterList(chaptersUrl: String, dataBeanId: Int): List<ChapterBean> {
        var chapterList = ArrayList<ChapterBean>()
        var url = dataJson.getString("url");
        val xqJson = dataJson.getJSONObject("xq")
        if (!chaptersUrl.startsWith("http")) {
            url += chaptersUrl
        } else {
            url = chaptersUrl
        }
        val html = HttpClient.get(url, mapOf(), dataJson.getString("ecode"))
        if (html == null || html.isEmpty()) {
            return chapterList
        }
        val document = Jsoup.parse(html)
        val xqZjJson = xqJson.getJSONObject("zj")
        val zjXpath = xqZjJson.getString("xpath")
        val booklistmain = document.select(zjXpath)
        val xqZjItemJson = xqZjJson.getJSONObject("item")
        val xqZjItemXpath = xqZjItemJson.getString("xpath")
        val listmaindds = booklistmain.select(xqZjItemXpath)
        for ((index, listmaindd: Element) in listmaindds.withIndex()) {
            var chapter = ChapterBean()
            chapter.dataBeanId = dataBeanId
            xqZjItemJson.getString("name").let {
                chapter.name = listmaindd.select(it).text()
            }
            xqZjItemJson.getString("url").let {
                chapter.url = listmaindd.select(it).attr("href")
            }
            chapter.index = index
            chapterList.add(chapter)
        }
        return chapterList
    }

    override suspend fun getChapterContent(chapterUrl: String): String {
        var content = ""
        var url = dataJson.getString("url");
        val nrJson = dataJson.getJSONObject("nr")
        if (!chapterUrl.startsWith("http")) {
            url += chapterUrl
        } else {
            url = chapterUrl
        }
        val html = HttpClient.get(url, mapOf(), dataJson.getString("ecode"))
        if (html == null) {
            return ""
        }
        val document = Jsoup.parse(html)
        nrJson.getString("zjnr").let {
            content = document.select(it).html()
        }
        return content.replace(Regex("(<br>.?<br>)|(<p.*</p>)"), "\n").replace("&nbsp;", " ")
    }

    override suspend fun getSearchByKeyword(keyword: String): List<DataBean> {
        var dataBens = ArrayList<DataBean>()
        val ss = dataJson.getJSONObject("ss");
        val url = (dataJson.getString("url") + ss.getString("cxurl")).replace("$keyword", keyword);
        if ("json".equals(ss.getString("type"))) {
            val jsonString = HttpClient.get(url, mapOf())
            println(jsonString)
            if (jsonString == "1" || jsonString == null) {
                return dataBens;
            }
            val reqJson = JSON.parseArray(jsonString)
            for (jsonItem in reqJson) {
                var itemDataBean: DataBean = DataBean()
                val itemData = JSONObject.from(jsonItem)
                itemDataBean.name = itemData.getString(ss.getString("mc"))
                itemDataBean.cover = itemData.getString(ss.getString("tp"))
                itemDataBean.author = itemData.getString(ss.getString("zz"))
                itemDataBean.desc = itemData.getString(ss.getString("jj"))
                itemDataBean.url = itemData.getString(ss.getString("url"))
                dataBens.add(itemDataBean)
            }
        } else {
            var html = HttpClient.getWebviewUrl(url, "")
            if (html == "1" || html == null) {
                return dataBens
            }
            println(html)
        }
        return dataBens
    }

}